﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using ColorApplication.Helper;
using System.Configuration;

namespace ColorApplication.color
{
    public partial class Attribute : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Checking whether Admin or Not. AdminID key is in web.config
            if (Request.QueryString["id"] != null && Request.QueryString["id"] != "" && Request.QueryString["id"] == ConfigurationManager.AppSettings["AdminID"].ToString())
            {
                Clear();
            }
            else
            {
                Response.Redirect("~/Default.aspx");
            }
        }

        public void Clear()
        {
            // Clear Error And Success label Every Post Bak
            SuccesLabel.Text = "";
            ErrorLabel.Text = "";

        }

        protected void AttributeGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                // Change Deatils view Mode to edit
                AttributeDetailsView.ChangeMode(DetailsViewMode.Edit);
            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void AttributeGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            try
            {
                // Bind java Script for Are you Sure to Delete Confirm Box
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    LinkButton delinkbutton = (LinkButton)e.Row.FindControl("DeleteLinkButton");
                    delinkbutton.OnClientClick = "return getDeleteMessage()";
                    HyperLink ColorAttributeHyperLink = (HyperLink)e.Row.FindControl("ColorAttributeHyperLink");
                    HyperLink FamiliesHyperLink = (HyperLink)e.Row.FindControl("FamiliesHyperLink");

                    ColorAttributeHyperLink.NavigateUrl += "&id=" + Request.QueryString["id"];
                    FamiliesHyperLink.NavigateUrl += "&id=" + Request.QueryString["id"];
                    Label lblDirection = (Label)e.Row.FindControl("lblDirection");
                    if (lblDirection.Text.Equals("1"))
                    {
                        lblDirection.Text = "Good";
                    }
                    else
                    {
                        lblDirection.Text = "Bad";
                    }
                }
            }
            catch (Exception err)
            {

                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void AttributeDetailsView_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {
            try
            {
                // Show Success Message 
                // Grid data Binding
                SuccesLabel.Text = "Record updated successfully.";
                AttributeDetailsView.ChangeMode(DetailsViewMode.Insert);
                AttributeGridView.DataBind();
            }
            catch (Exception err)
            {

                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void AttributeDetailsView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            try
            {
                // Show Success Message 
                // Grid data Binding
                SuccesLabel.Text = "Record inserted successfully.";
                AttributeDetailsView.ChangeMode(DetailsViewMode.Insert);
                AttributeGridView.DataBind();
            }
            catch (Exception err)
            {

                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void AttributeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int AttributeId = Convert.ToInt32(e.Keys["Id"].ToString());

                // This Function Check Record in ColorsAttribute Table
                if (CheckRecordColorsAttribute(AttributeId, "AttributeId") == true)
                {
                    ErrorLabel.Text = "This Arrtibute is used in colors attribute.Delete is not allowed.";
                    e.Cancel = true;
                    //Cancel And Show Error Message
                }
                else if (CheckAttributesInAttributesXAttributesfamilies(AttributeId) == true)  // This Function Check Record in Sub Color Table
                {
                    ErrorLabel.Text = "This Arrtibute is used in Attributes X Attributesfamilies.Delete is not allowed.";
                    e.Cancel = true;
                    //Cancel And Show Error Message
                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }

        public bool CheckRecordColorsAttribute(int RecordValue, string ColumnName)
        {
            // This Function Check Record in ColorsAttribute Table
            // if Record Found Return true
            //else return false

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { };

                SqlCommand cmd = SQLHelper.GetCommand(con, "CheckRecordColorsAttribute", parameters);
                con.Open();

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string RecordValuestr = dr[ColumnName].ToString();

                if (RecordValuestr != null && RecordValuestr != string.Empty)
                {
                    if (RecordValuestr == RecordValue.ToString())
                    {
                        return true;
                    }
                }

            }

            return false;

        }

        public bool CheckAttributesInAttributesXAttributesfamilies(int AttributeId)
        {
            // This Function Check AttributeId in AttributesXAttributesfamilies Table
            // if Record Found Return true
            //else return false

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@AttributeId", AttributeId) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "CheckAttributesInAttributesXAttributesfamilies", parameters);
                con.Open();

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                return true;

            }

            return false;

        }

        protected void AttributeDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            try
            {
                string oldDescription = e.OldValues["Description"].ToString();
                string newDescription = e.NewValues["Description"].ToString();

                if (oldDescription != newDescription)
                {
                    // This Function Check Record in Attribute for Dublicate Description name exist or Not
                    if (CheckDescriptionExistinAttribute(newDescription) == true)
                    {
                        ErrorLabel.Text = "Description already exists. Duplicate record is not allowed.";
                        e.Cancel = true;
                        //Cancel And Show Error Message
                    }

                }

            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }

        protected void AttributeDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            try
            {
                string Description = e.Values["Description"].ToString();
                // DropDownList InsertDropDownList =.FindControl("AttributeDetailsView") as DropDownList;
                // int Direction = Convert.ToInt32(InsertDropDownList.SelectedValue);
                int Direction = Convert.ToInt32(e.Values["Direction"].ToString());

                // This Function Check Record in Attribute for Dublicate Description name exist or Not
                if (CheckDescriptionExistinAttribute(Description))
                {
                    ErrorLabel.Text = "Description already exists. Duplicate record is not allowed.";
                    e.Cancel = true;
                    //Cancel And Show Error Message
                }


            }
            catch (Exception err)
            {
                ErrorLabel.Text = err.Message.ToString();
            }
        }

        public bool CheckDescriptionExistinAttribute(string Description)
        {
            // This Function Check Record in Attribute Table For Dublicate Description Name Exist or Not
            // if Record Found Return true
            //else return false

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Description", Description) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "CheckDescriptionExistinAttribute", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                return true;
            }

            return false;

        }

    }
}